<template>
  <div class="loan-approval">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>贷款审批</h3>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="贷款编号">
          <el-input v-model="searchForm.loanNo" placeholder="请输入贷款编号" clearable />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户姓名" clearable />
        </el-form-item>
        <el-form-item label="审批状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审批" value="pending" />
            <el-option label="审批中" value="processing" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 审批列表 -->
      <el-table :data="approvalList" style="width: 100%" v-loading="loading">
        <el-table-column prop="loanNo" label="贷款编号" width="180" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="loanAmount" label="贷款金额" width="150">
          <template #default="scope">
            {{ formatAmount(scope.row.loanAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="loanTerm" label="贷款期限" width="120">
          <template #default="scope">
            {{ scope.row.loanTerm }}个月
          </template>
        </el-table-column>
        <el-table-column prop="purpose" label="贷款用途" width="150" />
        <el-table-column prop="status" label="审批状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentNode" label="当前节点" width="120" />
        <el-table-column prop="submitTime" label="提交时间" width="180" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                link
                type="primary"
                @click="handleApproval(scope.row)"
                v-if="scope.row.status === 'pending' || scope.row.status === 'reviewing'"
              >
                审批
              </el-button>
              <el-button
                link
                type="primary"
                @click="viewDetail(scope.row)"
              >
                查看
              </el-button>
              <el-button
                link
                type="primary"
                @click="viewHistory(scope.row)"
              >
                历史
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialogVisible"
      title="贷款审批"
      width="60%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="approvalFormRef"
        :model="approvalForm"
        :rules="approvalRules"
        label-width="120px"
        v-loading="approvalLoading"
      >
        <el-divider>贷款信息</el-divider>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="贷款编号">{{ currentLoan.loanNo }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ currentLoan.customerName }}</el-descriptions-item>
          <el-descriptions-item label="贷款类型">{{ getLoanTypeText(currentLoan.loanType) }}</el-descriptions-item>
          <el-descriptions-item label="贷款金额">{{ formatAmount(currentLoan.loanAmount) }}</el-descriptions-item>
          <el-descriptions-item label="贷款期限">{{ currentLoan.loanTerm }}个月</el-descriptions-item>
          <el-descriptions-item label="贷款用途">{{ currentLoan.purpose }}</el-descriptions-item>
          <el-descriptions-item label="还款方式">{{ getRepaymentMethodText(currentLoan.repaymentMethod) }}</el-descriptions-item>
          <el-descriptions-item label="担保方式">{{ getGuaranteeTypeText(currentLoan.guaranteeType) }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>审批决定</el-divider>
        <el-form-item label="审批决定" prop="decision">
          <el-radio-group v-model="approvalForm.decision">
            <el-radio label="approve">通过</el-radio>
            <el-radio label="reject">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审批意见" prop="comment">
          <el-input
            v-model="approvalForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入审批意见"
          />
        </el-form-item>
        
        <el-form-item label="批准金额" prop="approvedAmount" v-if="approvalForm.decision === 'approve'">
          <el-input-number
            v-model="approvalForm.approvedAmount"
            :min="1000"
            :max="currentLoan.loanAmount"
            :step="1000"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="放款日期" prop="loanDate" v-if="approvalForm.decision === 'approve'">
          <el-date-picker
            v-model="approvalForm.loanDate"
            type="date"
            placeholder="选择放款日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitApproval">提交审批</el-button>
          <el-button @click="approvalDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 贷款详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="贷款详情"
      width="60%"
      :before-close="handleDetailClose"
    >
      <loan-detail v-if="detailDialogVisible" :loan-id="currentLoanId" />
    </el-dialog>

    <!-- 审批历史对话框 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="审批历史"
      width="60%"
      :before-close="handleHistoryClose"
    >
      <approval-history v-if="historyDialogVisible" :loan-id="currentLoanId" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { loanApplyApi, loanApprovalApi } from '@/api/loan'
import LoanDetail from './components/LoanDetail.vue'
import ApprovalHistory from './components/ApprovalHistory.vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const approvalFormRef = ref(null)
const loading = ref(false)
const approvalLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const approvalList = ref([])
const currentLoan = ref({})
const currentLoanId = ref('')

// 对话框
const approvalDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const historyDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  loanNo: '',
  customerName: '',
  status: ''
})

// 审批表单
const approvalForm = reactive({
  applyId: '',
  decision: 'approve',
  comment: '',
  approvedAmount: 0,
  loanDate: ''
})

// 审批表单验证规则
const approvalRules = {
  decision: [
    { required: true, message: '请选择审批决定', trigger: 'change' }
  ],
  comment: [
    { required: true, message: '请输入审批意见', trigger: 'blur' },
    { min: 5, message: '审批意见至少需要5个字符', trigger: 'blur' }
  ],
  approvedAmount: [
    { 
      required: true, 
      message: '请输入批准金额', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (approvalForm.decision === 'approve' && (!value || value <= 0)) {
          callback(new Error('批准金额必须大于0'))
        } else {
          callback()
        }
      }
    }
  ],
  loanDate: [
    {
      required: true,
      message: '请选择放款日期',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (approvalForm.decision === 'approve' && !value) {
          callback(new Error('请选择放款日期'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 获取审批列表
const getApprovalList = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const res = await loanApprovalApi.getPendingList(params)
    console.log('审批列表接口返回:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理不同的数据结构
      let listData = []
      let totalCount = 0
      
      // 检查返回数据结构
      if (res.data && res.data.list) {
        // 新的数据结构: {code:"200", msg:"操作成功", data:{total:1, pageSize:10, list:[...], pageNum:1}}
        listData = res.data.list
        totalCount = res.data.total
      } else if (res.data && res.data.data && res.data.data.list) {
        // 嵌套结构: {code:200, msg:"", data:{code:200, msg:"", data:{list:[], total:0}}}
        listData = res.data.data.list
        totalCount = res.data.data.total
      } else if (res.data && Array.isArray(res.data)) {
        // 直接返回数组: {code:200, data:[...]}
        listData = res.data
        totalCount = res.data.length
      } else {
        console.warn('未识别的返回数据结构:', res)
        listData = []
        totalCount = 0
      }
      
      approvalList.value = listData
      total.value = totalCount
      
      if (!listData || listData.length === 0) {
        ElMessage.warning('未查询到待审批的贷款数据')
      }
    } else {
      ElMessage.error(res.msg || res.message || '获取审批列表失败')
    }
  } catch (error) {
    console.error('获取审批列表出错:', error)
    ElMessage.error('获取审批列表失败')
  } finally {
    loading.value = false
  }
}

// 获取贷款详情
const getLoanDetail = async (id) => {
  try {
    approvalLoading.value = true
    const res = await loanApplyApi.getInfo(id)
    console.log('贷款详情接口返回:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理可能的嵌套数据结构
      let detailData = null
      
      if (res.data && typeof res.data === 'object' && !Array.isArray(res.data)) {
        // 直接是对象结构
        detailData = res.data
      } else if (res.data && res.data.data && typeof res.data.data === 'object') {
        // 嵌套结构
        detailData = res.data.data
      } else {
        console.warn('未识别的贷款详情数据结构:', res)
        ElMessage.error('获取贷款详情数据格式异常')
        return
      }
      
      currentLoan.value = detailData
      // 初始化审批表单
      approvalForm.applyId = id
      approvalForm.approvedAmount = detailData.loanAmount
      
      // 默认放款日期为当前日期
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      approvalForm.loanDate = `${year}-${month}-${day}`
    } else {
      ElMessage.error(res.msg || res.message || '获取贷款详情失败')
    }
  } catch (error) {
    console.error('获取贷款详情出错:', error)
    ElMessage.error('获取贷款详情失败')
  } finally {
    approvalLoading.value = false
  }
}

// 查询
const handleSearch = () => {
  currentPage.value = 1
  getApprovalList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  getApprovalList()
}

// 处理审批
const handleApproval = async (row) => {
  currentLoanId.value = row.id
  await getLoanDetail(row.id)
  approvalDialogVisible.value = true
}

// 查看详情
const viewDetail = (row) => {
  currentLoanId.value = row.id
  detailDialogVisible.value = true
}

// 查看历史
const viewHistory = (row) => {
  currentLoanId.value = row.id
  historyDialogVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailDialogVisible.value = false
  currentLoanId.value = ''
}

// 关闭历史对话框
const handleHistoryClose = () => {
  historyDialogVisible.value = false
  currentLoanId.value = ''
}

// 关闭审批对话框
const handleDialogClose = () => {
  approvalDialogVisible.value = false
  // 重置表单
  resetApprovalForm()
}

// 重置审批表单
const resetApprovalForm = () => {
  approvalForm.applyId = ''
  approvalForm.decision = 'approve'
  approvalForm.comment = ''
  approvalForm.approvedAmount = 0
  approvalForm.loanDate = ''
}

// 提交审批
const submitApproval = async () => {
  if (!approvalFormRef.value) return
  
  await approvalFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        approvalLoading.value = true
        const data = { ...approvalForm }
        
        // 转换数值类型
        data.approvedAmount = Number(data.approvedAmount)
        
        const res = await loanApprovalApi.submit(data)
        console.log('审批提交返回:', res) // 调试日志
        
        if (res.code === 200 || res.code === '200') {
          ElMessage.success('审批提交成功')
          approvalDialogVisible.value = false
          resetApprovalForm()
          getApprovalList()
        } else {
          ElMessage.error(res.msg || res.message || '审批提交失败')
        }
      } catch (error) {
        console.error('审批提交出错:', error)
        ElMessage.error('审批提交失败')
      } finally {
        approvalLoading.value = false
      }
    } else {
      console.log('表单验证失败:', fields)
      ElMessage.error('请完善审批信息')
    }
  })
}

// 格式化金额
const formatAmount = (amount) => {
  return amount ? '¥' + amount.toLocaleString() : '¥0'
}

// 获取贷款类型文本
const getLoanTypeText = (type) => {
  const map = {
    personal: '个人消费贷',
    house: '住房贷款',
    car: '车辆贷款',
    business: '经营贷款'
  }
  return map[type] || type
}

// 获取还款方式文本
const getRepaymentMethodText = (method) => {
  const map = {
    equalInstallment: '等额本息',
    equalPrincipal: '等额本金',
    interestFirst: '先息后本',
    bulletPayment: '一次性还本付息'
  }
  return map[method] || method
}

// 获取担保方式文本
const getGuaranteeTypeText = (type) => {
  const map = {
    credit: '信用',
    guarantee: '保证',
    mortgage: '抵押',
    pledge: '质押'
  }
  return map[type] || type
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    pending: '待审批',
    processing: '审批中',
    reviewing: '审批中',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return map[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    processing: 'primary',
    reviewing: 'primary',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || ''
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  getApprovalList()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getApprovalList()
}

onMounted(() => {
  getApprovalList()
  
  // 检查是否有指定的贷款ID
  const id = route.query.id
  if (id) {
    currentLoanId.value = id
    handleApproval({ id })
  }
})
</script>

<style scoped>
.loan-approval {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-divider {
  margin: 20px 0;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 